package org.travel_system.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.travel_system.pojo.Favorite;
import org.travel_system.service.FavoritesService;
import org.travel_system.service.UserService;
import org.travel_system.utils.Result;
import org.travel_system.utils.ThreadLocalUtil;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/favorites")
public class FavoritesController {

    private final FavoritesService favoritesService;
    private final UserService userService;

    @Autowired
    public FavoritesController(FavoritesService favoritesService, UserService userService) {
        this.favoritesService = favoritesService;
        this.userService = userService;
    }

    //添加收藏
    @PostMapping("/add")
    public Result<?> addFavorite(@RequestBody Favorite favorite) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        int userId = userService.findUserId(username);
        favorite.setToursId(userId);
        return favoritesService.add(favorite) > 0?
                Result.success() :
                Result.error("添加收藏失败");
    }


    //取消收藏
    @DeleteMapping("/{favoritesId}")
    public Result<?> deleteFavorite(@PathVariable int favoritesId) {
        return favoritesService.delete(favoritesId) > 0?
                Result.success() :
                Result.error("取消收藏失败");
    }

    //查看收藏列表
    @GetMapping("/list")
    public Result<List<Favorite>> getFavoriteList() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        int userId = userService.findUserId(username);
        return Result.success(favoritesService.getFavoriteList(userId));
    }
}
